﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace KgUtils
{
    /// <summary>
    /// Extension applied to all objects
    /// Some methods inspired from dvp.net http://dvp-net.developpez.com/
    /// </summary>
    public static partial class ObjectExtension
    {
        /// <summary>
        /// Returns the current value if not null, else returns the default value specified
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj">Current value.</param>
        /// <param name="defaultValue">Value to return if current value is null.</param>
        /// <returns></returns>
        public static T Default<T>(this T obj, T defaultValue) where T : class
        {
            return obj ?? defaultValue;
        }


        /// <summary>
        /// Check that a value is in the list
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="value">Current value.</param>
        /// <param name="list">List in which the value may be present</param>
        /// <returns>true if the value is in the list, else returns false</returns>
        public static bool In<T>(this T value, params T[] list)
        {
            return list.Contains(value);
        }

        /// <summary>
        /// Check that a value is in the list
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="value">Current value.</param>
        /// <param name="list">List in which the value may be present</param>
        /// <returns>true if the value is in the list, else returns false</returns>
        public static bool In<T>(this T value, IEnumerable<T> list)
        {
            return list.Contains(value);
        }

        /// <summary>
        /// Converts an object in the specified type. Throws an exception if it fails.
        /// </summary>
        /// <typeparam name="T">Target type</typeparam>
        /// <param name="value">Current object to convert.</param>
        /// <returns>The converted object</returns>
        public static T ConvertTo<T>(this object value)
        {
            return (T)Convert.ChangeType(value, typeof(T));
        }

        /// <summary>
        /// Performs an Equals between two object without the risk of throwing NullReferenceException
        /// </summary>
        /// <typeparam name="T">Objects type</typeparam>
        /// <param name="obj">Current object</param>
        /// <param name="other">Object to compare</param>
        /// <returns>true if the objects are equals, else false.</returns>
        public static bool SafeEquals<T>(this T obj, T other)
        {
            return object.Equals(obj, other);
        }
    }
}
